<script setup lang="ts">
import { reactive, onMounted } from 'vue';
import dayjs from 'dayjs';
import {
  getCurrentInstance,
  navigateTo,
  redirectTo,
  setNavigationBarTitle,
  showLoading,
  hideLoading,
} from '@tarojs/taro';
import {
  Search2 as AppNutIconSearch2,
  Horizontal as AppNutIconHorizontal,
} from '@nutui/icons-vue-taro';
import {
  WORK_ORDER_STATUS,
  WORK_ORDER_STATUS_COLOR,
  WORK_ORDER_STATUS_BG_COLOR,
} from '/@/common/constant';
import {
  QUERY_APP_WORK_ORDER_LIST,
  COUNT_APP_STATUS_QUANTITY,
} from '/@/api/modules/order/app-work-order';
import { LOGIN_APP } from '/@/api/modules/base/app-sys-user';
import IMG_ICON_COOPERATE from '/@/assets/image/icon/cooperate.png';
import IMG_ICON_SPEED from '/@/assets/image/icon/speed.png';

/**
 * 页面类型
 */
const pageTypeObj = {
  default: '我的工单',
  'report-history': '历史工单',
};

/**
 * @description 当前路由信息
 */
const params = getCurrentInstance().router?.params as {
  /**
   * 页面类型
   * - default 默认工单列表
   * - report-history 历史工单
   */
  pageType: keyof typeof pageTypeObj;
};

const state = reactive<{
  /**
   * 当前页
   */
  activePage: number;
  /**
   * 加载状态
   */
  loading: boolean;
  /**
   * 加载完成状态
   */
  finished: boolean;
  /**
   * 发起人ID
   */
  releaseUserId?: string;
  /**
   * 解决者ID
   */
  resolverUserId?: string;
  /**
   * 列表
   */
  list: AppSysWorkOrder.Dto[];
  /**
   * 接单状态
   */
  statusQuantity: {
    [x in keyof typeof WORK_ORDER_STATUS]?: string;
  };
  /**
   * 当前工单状态
   */
  activeStatus?: keyof typeof WORK_ORDER_STATUS;
  /**
   * 工单编号或地点
   */
  orderCodeOrAreaName?: string;
  /**
   * 创建时间开始 格式毫秒
   */
  createTimeBegin?: number;
  /**
   * 创建时间结束 格式毫秒
   */
  createTimeEnd?: number;
  /**
   * 创建时间筛选气泡弹出框是否显示
   */
  createTimeFilterPopoverVisible?: boolean;
}>({
  activePage: 1,
  loading: false,
  finished: false,
  releaseUserId: '',
  resolverUserId: '',
  list: [],
  statusQuantity: {},
  activeStatus: undefined,
  orderCodeOrAreaName: undefined,
  createTimeBegin: undefined,
  createTimeEnd: undefined,
  createTimeFilterPopoverVisible: false,
});

/**
 * @description 列表查询
 * @param {Number} page -当前页
 * @param {Number} pageSize -每页条数
 */
function queryList(page: number = 1, pageSize: number = 15) {
  if (!page && state.finished) return;
  state.loading = true;
  let status: string[] = [];
  if (state.activeStatus) {
    if (state.activeStatus === 'task_suspend') {
      status = ['task_suspend', 'task_suspend_review'];
    } else if (state.activeStatus === 'task_complete') {
      status = ['task_complete', 'task_review'];
    } else {
      status = [state.activeStatus];
    }
  }
  QUERY_APP_WORK_ORDER_LIST({
    comQuery: { page, pageSize },
    workOrderDto: {
      releaseUserId: state.releaseUserId,
      resolverUserId: state.resolverUserId,
    },
    status,
    orderCodeOrAreaName: state.orderCodeOrAreaName,
    createTimeBegin: state.createTimeBegin,
    createTimeEnd: state.createTimeEnd,
  })
    .then((res) => {
      if (
        state.activePage >=
        (res.comQuery?.pageCount ||
          (res.comQuery?.totalCount as number) / (res.comQuery?.pageSize as number) ||
          1)
      )
        state.finished = true;
      if (!res.workOrderDto || !res.workOrderDto.length) return;

      res.workOrderDto.forEach((item) => state.list.push(item));

      state.activePage += 1;
      state.loading = false;
      hideLoading();
    })
    .catch(() => {
      state.loading = false;
      hideLoading();
    });
}

/**
 * @function 加载
 */
function onLoading() {
  if (state.finished) return;

  queryList(state.activePage);
}

onMounted(() => {
  state.activePage = 1;
  state.loading = true;
  state.finished = false;
  state.list = [];
  showLoading();

  if (params.pageType === 'report-history') {
    LOGIN_APP().then((res) => {
      state.releaseUserId =
        process.env.APP_EDITION === 'hgy' ? res.sysUserDto.uaaUserId : res.sysUserDto.id;
      state.activeStatus = undefined;
      state.resolverUserId = undefined;
      onLoading();
    });
  } else {
    params.pageType = 'default';
    COUNT_APP_STATUS_QUANTITY({}).then((res) => {
      state.statusQuantity.task_receive = `待接单(${
        res.statusQuantity.task_receive > 99 ? '99+' : res.statusQuantity.task_receive || 0
      })`;
      state.statusQuantity.task_process = `处理中(${
        res.statusQuantity.task_process > 99 ? '99+' : res.statusQuantity.task_process || 0
      })`;
      state.statusQuantity.task_suspend = `挂起(${
        res.statusQuantity.task_suspend + res.statusQuantity.task_suspend_review > 99
          ? '99+'
          : res.statusQuantity.task_suspend + res.statusQuantity.task_suspend_review || 0
      })`;
      state.statusQuantity.task_complete = `已完成(${
        res.statusQuantity.task_review + res.statusQuantity.task_complete > 99
          ? '99+'
          : res.statusQuantity.task_review + res.statusQuantity.task_complete || 0
      })`;

      state.activeStatus = 'task_receive';
      LOGIN_APP().then((res) => {
        state.releaseUserId = undefined;
        state.resolverUserId =
          process.env.APP_EDITION === 'hgy' ? res.sysUserDto.uaaUserId : res.sysUserDto.id;
        onLoading();
      });
    });
  }

  setNavigationBarTitle({
    title: pageTypeObj[params.pageType],
  });
});
</script>

<template>
  <view class="work-order-list app-page--1">
    <app-navbar :title="pageTypeObj[params.pageType]" />
    <nut-tabs
      v-if="params.pageType === 'default'"
      v-model="state.activeStatus"
      auto-height
      title-scroll
      @change="
        () => {
          state.activePage = 1;
          state.finished = false;
          state.list = [];
          state.orderCodeOrAreaName = undefined;
          state.createTimeBegin = undefined;
          state.createTimeEnd = undefined;
          onLoading();
        }
      "
    >
      <nut-tab-pane
        v-for="(label, key) in state.statusQuantity"
        :key="key"
        :title="label"
        :pane-key="key"
      />
    </nut-tabs>
    <nut-tabs
      v-else-if="params.pageType === 'report-history'"
      model-value="record"
      @click="
        ({ paneKey }) => {
          if (paneKey === 'push') {
            redirectTo({ url: '/pages/work-order/edit/index' });
          }
        }
      "
    >
      <nut-tab-pane title="新建上报" pane-key="push" />
      <nut-tab-pane title="上报记录" pane-key="record" />
    </nut-tabs>
    <nut-searchbar
      v-model="state.orderCodeOrAreaName"
      placeholder="请输入工单号/地点"
      @search="
        () => {
          state.activePage = 1;
          state.finished = false;
          state.list = [];
          onLoading();
        }
      "
    >
      <template v-slot:leftin>
        <app-nut-icon-search-2 />
      </template>
      <template v-slot:rightout>
        <nut-popover
          v-model:visible="state.createTimeFilterPopoverVisible"
          :list="[
            { name: '全部', begin: undefined, end: undefined },
            {
              name: '今日',
              begin: dayjs(dayjs().format('YYYY-MM-DD 00:00:00')).valueOf(),
              end: dayjs(dayjs().format('YYYY-MM-DD 23:59:59')).valueOf(),
            },
            {
              name: '本周',
              begin: dayjs(dayjs().day(1).format('YYYY-MM-DD 00:00:00')).valueOf(),
              end: dayjs(dayjs().format('YYYY-MM-DD 23:59:59')).valueOf(),
            },
            {
              name: '本月',
              begin: dayjs(dayjs().format('YYYY-MM-01 00:00:00')).valueOf(),
              end: dayjs(dayjs().format('YYYY-MM-DD 23:59:59')).valueOf(),
            },
          ]"
          location="bottom-end"
          @choose="
            ({ begin, end }) => {
              state.createTimeBegin = begin;
              state.createTimeEnd = end;
              state.activePage = 1;
              state.finished = false;
              state.list = [];
              onLoading();
            }
          "
        >
          <template #reference>
            <view class="work-order-list__create-time-filter-btn">
              <app-nut-icon-horizontal />
              <text>筛选</text>
            </view>
          </template>
        </nut-popover>
      </template>
    </nut-searchbar>
    <scroll-view
      class="app-page__wrapper"
      :scroll-y="true"
      :lower-threshold="100"
      @scrolltolower="onLoading()"
    >
      <view class="work-order-list__wrapper">
        <view
          v-for="item in state.list"
          :key="item.id || ''"
          class="work-order-item"
          @click="
            navigateTo({
              url: `/pages/work-order/detail/index?id=${item.id}&from=${params.pageType}`,
            })
          "
        >
          <view class="work-order-item__header">
            <view class="work-order-item__header--left">
              <text class="work-order-item__code">{{ item.orderCode }}</text>
              <image
                v-if="item.hastenStatus === 2"
                class="work-order-item__icon"
                :src="IMG_ICON_SPEED"
              />
              <image
                v-if="item.cooperateStatus === 1"
                class="work-order-item__icon"
                :src="IMG_ICON_COOPERATE"
              />
            </view>
            <view class="work-order-item__header--right">
              <text
                class="work-order-item__status"
                :style="{
                  color: item.status ? WORK_ORDER_STATUS_COLOR[item.status] : '#999',
                  backgroundColor: item.status ? WORK_ORDER_STATUS_BG_COLOR[item.status] : '#999',
                }"
              >
                {{ item.status ? WORK_ORDER_STATUS[item.status] : '-' }}
              </text>
            </view>
          </view>
          <view class="work-order-item__description">
            <view class="work-order-item__description--left">
              <text class="nut-ellipsis">{{ item.description }}</text>
            </view>
          </view>
          <view>
            <nut-row>
              <nut-col span="12">
                <text>来源:&nbsp;&nbsp;</text>
                <text>{{ item.orderSourceName || '-' }}</text>
              </nut-col>
              <nut-col span="12">
                <text>提单人:&nbsp;&nbsp;</text>
                <text>{{ item.releaseUserName || '-' }}</text>
              </nut-col>
            </nut-row>
          </view>
          <view>
            <text>地点:&nbsp;&nbsp;</text>
            <text>
              {{ item.areaName || '-' }}
            </text>
          </view>
        </view>
      </view>

      <view class="app-page__list-tips">
        <text v-if="!state.list.length">暂无数据！</text>
        <text v-else-if="state.list.length && state.loading">加载中...</text>
        <text v-else-if="state.list.length && state.finished">加载完成!</text>
      </view>
    </scroll-view>
  </view>
</template>

<style lang="scss">
@import './index.scss';
</style>
